package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLockTest
 * condition.await 可以释放锁 方法大概流程 unlock wait lock
 * condition.signal
 */
public class Client {
    private ReentrantLock lock = new ReentrantLock(true);
    private Condition condition = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        Client client = new Client();
        client.run();

    }

    private void run() throws InterruptedException {

        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"开始等待");
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+"有多少线程等待锁"+lock.getQueueLength());
                condition.await(10, TimeUnit.SECONDS);
                System.out.println("等待完成");
                lock.unlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        Thread.sleep(100);
        new Thread(()->{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"开始通知");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            condition.signal();
            System.out.println("通知完成");
            lock.unlock();
        }).start();






    }
}
